<template>
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>人员管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>教师管理</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
<!--数据搜索  -->
  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="院系" prop="dept">
        <el-select
            v-model="searchFormModel.dept"
            placeholder="请选择院系"
            clearable  style="width:140px">
          <el-option
              v-for="item in deptValue"
              :key="item.dept"
              :label="item.deptname"
              :value="item.deptid"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchOnSubmit">
          <el-icon><Search /></el-icon>  查询
        </el-button>
        <el-button type="success" @click="dialogAddState=true" >
          <el-icon><Plus /></el-icon>  添加
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <!--  数据表格-->
  <div style="margin: 20px" >
    <el-table :data="teacherInfo" stripe border style="width: 100%">
      <el-table-column prop="tid" label="职工号" />
      <el-table-column prop="tname" label="教师姓名"/>
      <el-table-column prop="dept" label="所负责院系"  :formatter="attributeFormatter"/>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="tableEditHandler(scope.$index, scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="tableDeleteHandler(scope.$index, scope.row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--  分页-->
  <div class="page">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8,10]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--  编辑-->
  <el-dialog v-model="dialogEditState" title="修改教师信息" width="380">
    <div>
      <el-form ref="formEditRef" :model="formEdit" label-width="120px">
        <el-form-item prop="tid" label="职工号">
          <el-input v-model="formEdit.tid" disabled ></el-input>
        </el-form-item>
        <el-form-item prop="tname" label="教师姓名">
          <el-input v-model="formEdit.tname" disabled ></el-input>
        </el-form-item>
        <el-form-item prop="dept" label="负责院系">
            <el-select  v-model="formEdit.dept">
            <el-option label="全部" value=""></el-option>
            <el-option
                v-for="item in deptValue"
                :key="item.dept"
                :label="item.deptname"
                :value="item.deptid"
            />
            </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>
<!--添加 -->
  <el-dialog v-model="dialogAddState" title="添加教师信息" width="380">
    <div>
      <el-form ref="formAddRef" :rules="formAddRules" :model="formAdd" label-width="120px">
        <el-form-item prop="tid" label="职工号">
          <el-input v-model="formAdd.tid" maxlength="8" show-word-limit></el-input>
        </el-form-item>
        <el-form-item prop="tname" label="教师姓名">
          <el-input v-model="formAdd.tname" maxlength="4" ></el-input>
        </el-form-item>
        <el-form-item prop="tpass" label="密码">
          <el-input v-model="formAdd.tpass" type="password" maxlength="6" ></el-input>
        </el-form-item>
        <el-form-item prop="dept" label="负责院系">
          <el-select  v-model="formAdd.dept">
            <el-option label="全部" value=""></el-option>
            <el-option
                v-for="item in deptValue"
                :key="item.dept"
                :label="item.deptname"
                :value="item.deptid"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogAddOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script setup>
import {ArrowRight, Delete, Edit, Search,Plus} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from "vue";
import request from "../../../utils/freshman";
import {ElMessage, ElMessageBox} from "element-plus";
onMounted(()=>{
  getTeacher();
  getDept();
})
//院系所对应的值
const deptValue=ref([]);
const getDept=()=>{
  request({
    url:'/dept/all',
    method:'get'
  }).then((req)=>{
    console.log(req)
    if (200==req.data.errorCode){
      deptValue.value=req.data.data;
    }
  })
}
const attributeFormatter=(row, column, cellValue)=> {
  for (let i=0;i<deptValue.value.length;i++){
    if (cellValue== deptValue.value[i].deptid){
      return deptValue.value[i].deptname
    }
  }
}

//添加的校验规则
const formAddRules={
      tid: [
        { required: true, message: '职工号不能为空', trigger: 'blur' },
        { pattern: /^\d+$/, message: '职工号只能为数字', trigger: 'blur' }
      ],
      tname: [
        { required: true, message: '教师姓名不能为空', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名只能包含汉字', trigger: 'blur' }
      ],
      tpass: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { pattern:  /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{6,})$/, min: 6,
          message: '密码是由数字和英文组成且长度为6位', trigger: 'blur' },
      ],
      dept: [
        { required: true, message: '负责院系不能为空', trigger: 'change' }
      ]
};
//分页
const currentPage = ref(1)
const pageSize = ref(8)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const teacherInfo=ref([])
//搜索
const searchFormRef=ref();
const searchFormModel=reactive({
  tname:'',
  tid:'',
  dept:''
})

const getTeacher=()=>{
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    // 初始时不包含其他参数
  };
  if (searchFormModel.tname && searchFormModel.tname.trim() !== ''){
    params.tname=searchFormModel.tname.trim();
  }
  if (searchFormModel.tid && searchFormModel.tid.trim() !== ''){
    params.tid=searchFormModel.tid.trim();
  }
  if (searchFormModel.dept){
    params.dept=searchFormModel.dept;
  }
  request({
    url:'/admin/teacher/page',
    method:'get',
    params,
  }).then((req)=>{
    console.log(req)
    if (200==req.data.errorCode){
      teacherInfo.value=req.data.data.records;
      totals.value=req.data.data.total;
    }
  })
}
const searchOnSubmit=()=>{
  getTeacher();
}
const handleSizeChange = (val) => {
  pageSize.value=val;
  getTeacher()
}
const handleCurrentChange = (val) => {
  currentPage.value=val;
  getTeacher()
}
///////////////添加相关/////////////////
// 新增表单引用
const formAddRef = ref()
// 新增表单初始化数据
const formAddData = {
  tid:'',
  tname:'',
  tpass:'',
  dept:'',
  del:''
}
const dialogAddState = ref(false)
const dialogAddOnSubmit = () => {
  request({
    method:'post',
    url:'/admin/teacher/add',
    params:formAdd,
  }).then(req=>{
    if (200 == req.data.errorCode){
      ElMessage({
        type:'success',
        message:req.data.msg
      })
      Object.assign(formAdd , formAddData)
      getTeacher();
    }
  })
  dialogAddState.value=false;
}
const dialogAddOnReset = () => {
  // 清空表单数据
  Object.assign(formAdd , formAddData)
  // 关闭对话框
  dialogAddState.value = false
}

// 新增表单绑定数据模型
const formAdd = reactive({...formAddData})   // ...formAddData 解构formAddData

//编辑
const formEditRef = ref()
const formEditData = {
  tid:'',
  tname:'',
  dept:'',
}
// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData})
const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  formEdit.tid = rowData.tid
  formEdit.tname = rowData.tname
  formEdit.dept = rowData.dept
  dialogEditState.value = true
}
const dialogEditState = ref(false)
const dialogEditOnSubmit = () => {
  request({
    url:'/admin/teacher/update',
    method:'put',
    data:JSON.stringify(formEdit),
    headers:{'content-type' : "application/json;charset=UTF-8"}
  }).then(req=>{
    if (200==req.data.errorCode){
      ElMessage({
        type: 'success',
        message: '修改成功！',
      });
      getTeacher();
    }
  })
  dialogEditState.value = false
}
const dialogEditOnReset = () => {
  Object.assign(formEdit , formEditData)
  dialogEditState.value = false
}

//删除一条
const tableDeleteHandler = (rowIndex , rowData) => {
  ElMessageBox.confirm(
      '确认删除 : ' +rowData.tid,
      'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {//点击了删除按钮
    request({
      method:'delete',
      url:'/admin/teacher/delete/'+rowData.tid
    }).then(req=>{
      if (200==req.data.errorCode){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getTeacher();
      }
    })
  })
      .catch(() => {//点击了取消按钮
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
</script>
<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
.page{
  margin-left: 30%;
}
</style>